#include "trie_node.h"

TrieNode::TrieNode()
{
    m_data = ' ';
    m_flag = M_FLAG_NO_STR;
    m_children = nullptr;
    m_size = 0;
}

TrieNode::~TrieNode()
{
    if (m_children != nullptr)
    {
        for (int i = 0; i < m_size; i++)
        {
            delete m_children[i];
        }
        delete [] m_children;
        m_children = nullptr;
    }
    m_size = 0;
}

void TrieNode::insert(TrieNode * child, int idx)
{
    TrieNode ** children = new TrieNode*[m_size+1];
    for (int i = 0; i < idx; i++)
    {
        children[i] = m_children[i];
    }
    children[idx] = child;
    for (int i = idx; i < m_size; i++)
    {
        children[i + 1] = m_children[i];
    }
    if (m_children != nullptr)
    {
        delete [] m_children;
        m_children = nullptr;
    }
    m_children = children;
    m_size += 1;
}

void TrieNode::remove(int idx)
{
    auto child = m_children[idx];
    delete child;
    if (m_size == 1)
    {
        delete [] m_children;
        m_children = nullptr;
        m_size = 0;
        return;
    }
    TrieNode ** children = new TrieNode*[m_size-1];
    for (int i = 0; i < idx; i++)
    {
        children[i] = m_children[i];
    } 
    for(int i = idx + 1; i < m_size; i++)
    {
        children[i - 1] = m_children[i];
    }
    delete [] m_children;
    m_children = children;
    m_size -= 1;
}